var app = getApp()
Page({
    data: {
        ableAddFriend: false,
        show: false,
        second_hand: {
            _openid: '',
            nickName: '',
            avatarUrl: '', //头像
            cloud_imageID: [], //展现页面的data还需要存临时链接
            tempImageUrl: [],
            comments: [],
            isSell: true, //true 表示卖
            tag: '0', //0:百货，1：数码，2:书籍，3:电器，4，两轮，5，其他
            description: "",
            price: '',
            free: false,
            phone: 0,
            publish_time: "",
            time: '',
            formId: ""
        }
    },
    onLoad() {

    },
    onReady() {
        this.setData({
            show: true
        })
    },
    onUnload() {
        //console.log("sd")
    },

    doSubmit(e) {
        //console.log(app.globalData.userInfo.nickName)
        var time = new Date()
        var theTime = time.getFullYear() + '年' + (time.getMonth() + 1) + "月" + time.getDate() + "日 "
        if (time.getHours() < 10) {
            theTime += '0'
        }
        theTime += time.getHours() + ":"
        if (time.getMinutes() < 10) {
            theTime += '0'
        }
        theTime += time.getMinutes()
        this.setData({
            'second_hand.nickName': app.globalData.userInfo.nickName,
            'second_hand.avatarUrl': app.globalData.userInfo.avatarUrl,
            'second_hand._openid': app.globalData.openid,
            'second_hand.formId': e.detail.formId,
            'second_hand.publish_time': new Date().getTime(),
            'second_hand.time': theTime
        })
        if (this.data.second_hand.tempImageUrl.length < 1) {
            qq.showToast({
                icon: "none",
                title: "上传图片可以吸引注意力哦~"
            })
        } else if (this.data.second_hand.price.length < 1 && this.data.second_hand.free == false) {
            qq.showToast({
                icon: "none",
                title: "你还未输入价钱哦~"
            })
        } else if (this.data.second_hand.description.length < 3) {
            qq.showToast({
                icon: "none",
                title: "描述信息不能小于三个字哦~"
            })
        } else {
            this.uploadFile()
        }
    },
    uploadFile() {
        var i = 0 //正在上传第i
        var j = 0 //已经上传j
        var that = this
        var num = that.data.second_hand.tempImageUrl.length
        qq.showLoading({
            title: '上传' + i + '/' + num
        })
        var s = setInterval(function () {
            //console.log(i, j, num)
            if (j == num) {
                that.addToDB()
                clearInterval(s)
            } else if (j == i) {
                qq.hideLoading()
                qq.showLoading({
                    title: '上传' + i + '/' + num
                })
                i++;//此时i>j
                //下面进行上传图片，完成第i张上传后，j++，此时j=i
                const filePath = that.data.second_hand.tempImageUrl[i - 1]//第一张为0
                const cloudPath = 'second_hand/' + app.globalData.openid + new Date().getTime() + filePath.match(/\.[^.]+?$/)[0]
                var url = 'https://api.weixin.qq.com/tcb/uploadfile?access_token=' + app.globalData.access_token
                //console.log(url)
                qq.request({////////////////////////获取cos的url
                    url,
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    data: {
                        "env": app.globalData.myEnv,
                        "path": cloudPath
                    },
                    method: "POST",
                    success(res1) {//////////////////////////通过cos上传
                        //console.log(1, res1)
                        qq.uploadFile({
                            url: res1.data.url,
                            filePath,
                            name: 'file',
                            header: {
                                "Content-Type": "multipart/form-data"//记得设置
                            },
                            formData: {
                                key: cloudPath,
                                "Signature": res1.data.authorization,
                                "x-cos-security-token": res1.data.token,
                                "x-cos-meta-fileid": res1.data.cos_file_id
                            },
                            success(res2) { ////////////////////添加到数据库
                                that.setData({
                                    'second_hand.cloud_imageID': that.data.second_hand.cloud_imageID.concat(res1.data.file_id)
                                })
                                j++
                                //console.log(res2)
                            }, fail(msg) {
                                //console.log(msg)
                            }
                        })
                        //console.log(res1)
                    }
                })
            }
        }, 10)
    },
    addToDB() {
        var data = JSON.stringify(this.data.second_hand)
        qq.request({
            url: 'https://api.weixin.qq.com/tcb/databaseadd?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
            header: {
                'content-type': 'application/json' // 默认值
            }, method: "post",
            data: {
                "env": app.globalData.myEnv,
                "query": "db.collection(\"second_hand\").add({\
            data: "+ data + "\
        })"
            },
            success(res) {
                qq.hideLoading()
                qq.showToast({
                    title: "上传成功"
                })
                qq.navigateBack()
                //console.log(res.data)
            }
        })
    },

    input1(e) {
        this.setData({
            'second_hand.description': e.detail.value
        })
        // //console.log(e)
    },
    inputPhone(e) {
        // //console.log(e)
        this.setData({
            'second_hand.phone': e.detail.value - 0
        })
    },
    inputPrice(e) {
        //console.log(e)
        this.setData({
            'second_hand.price': e.detail.value - 0
        })
    },
    tagChange(e) {
        this.setData({
            'second_hand.tag': e.currentTarget.id
        })
        // //console.log(e)
    },
    radioChange(e) {
        //console.log(e)
        var isSell = e.detail.value == '0' ? true : false
        this.setData({
            'second_hand.isSell': isSell
        })
    },
    freePrice() {
        this.setData({
            'second_hand.free': !this.data.second_hand.free
        })
    },
    ChooseImage() {
        var that = this
        wx.chooseImage({ ////一次选择多张需要一张上传完毕后在上传
            count: 9, //默认9
            sourceType: ['album', 'camera'],
            sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都
            success: (res) => {
                this.zipImg(0, res.tempFilePaths)
            }
        });
    },
    zipImg(index, tempFilePaths) {
        var that = this
        if (index < tempFilePaths.length) {/////对每一个进行循环，获取连接后写入data
            qq.getImageInfo({
                src: tempFilePaths[index],
                success(res) {
                    //console.log(res)
                    var targetHeight = res.height
                    var targetWidth = res.width
                    var maxWidth = 500
                    var maxHeight = 1200 //2100以内 按宽度1000，高度自适应压缩，
                    //console.log(targetHeight, targetWidth)

                    if (targetWidth > maxWidth || targetHeight > maxHeight) {
                        if ((targetWidth / targetHeight) > (maxWidth / maxHeight)) {
                            targetHeight = Math.round(maxWidth * (targetHeight / targetWidth));
                            targetWidth = maxWidth;
                            // //console.log(">") 顺序什么都不能改变，易错
                        } else {
                            targetWidth = Math.round(maxHeight * (targetWidth / targetHeight));
                            targetHeight = maxHeight;
                        }
                    }
                    //console.log(targetHeight, targetWidth)

                    that.setData({
                        targetWidth: targetWidth,
                        targetHeight: targetHeight,
                        canvasShow: true
                    })
                    setTimeout(function () {
                        const ctx = qq.createCanvasContext('canvas');
                        ctx.drawImage(tempFilePaths[index], 0, 0, targetWidth, targetHeight);
                        ctx.draw(false, function () {
                            qq.canvasToTempFilePath({
                                canvasId: ('canvas'),
                                fileType: "jpg",
                                quality: 0.4,
                                destWidth: targetWidth,
                                destHeight: targetHeight,
                                success(res) {
                                    that.setData({
                                        'second_hand.tempImageUrl': that.data.second_hand.tempImageUrl.concat(res.tempFilePath),
                                        canvasShow: false
                                    })
                                    setTimeout(function () {
                                        index++
                                        that.zipImg(index, tempFilePaths);
                                        //console.log(res)
                                    }, 100)
                                }
                            })
                        })
                    }, 100)

                }
            })
        }
    },

    ViewImage(e) {
        wx.previewImage({
            urls: this.data.second_hand.tempImageUrl,
            current: e.currentTarget.dataset.url
        });
    },
    DelImg(e) {
        this.data.second_hand.tempImageUrl.splice(e.currentTarget.dataset.index, 1);
        this.setData({
            'second_hand.tempImageUrl': this.data.second_hand.tempImageUrl
        })
    },
})